var mssql = require('mssql')
var config = require('../config.js')

var dbHelper = {
    s: function (sql, cb, er) {
        var conn = new mssql.Connection(config.dbCfg)
        conn.connect()
            .then(function () {
                var req = new mssql.Request(conn)
                    .query(sql)
                    .then(function (rows) {
                        if (typeof cb == 'function') {
                            cb(rows)
                        }
                        conn.close()
                    })
            })
            .catch(function (err) {
                if (typeof er == 'function') {
                    er(err)
                }
                conn.close()
            });
    },
    qv: function (sql, v, cb, er) {
        var conn = new mssql.Connection(config.dbCfg)
        conn.connect()
            .then(function () {
                var vtype
                var req = new mssql.Request(conn)
                for (var p in v) {
                    switch (typeof v[p]) {
                        case 'string':
                            vtype = mssql.NVarChar
                            break
                        case 'number':
                            vtype = mssql.Float
                            break
                        case 'object':
                            vtype = mssql.DateTime
                            break
                    }
                    req.input(p, vtype, v[p])
                }
                req.query(sql)
                    .then(function (rows) {
                        if (typeof cb == 'function') {
                            cb(rows)
                        }
                        conn.close()
                    })
            })
            .catch(function (err) {
                if (typeof er == 'function') {
                    er(err)
                }
                conn.close()
            })
    },
    q: function (cb, er) {
        var conn = new mssql.Connection(config.dbCfg)
        conn.connect()
            .then(function () {
                var vtype
                var req = new mssql.Request(conn)
                    .query(sql)
                    .then(function (rows) {
                        if (typeof cb == 'function') {
                            cb(rows)
                        }
                        conn.close()
                    })
            })
            .catch(function (err) {
                if (typeof er == 'function') {
                    er(err)
                }
                conn.close()
            })
    }
}

module.exports = dbHelper